<template>
  <div class="container" >
    <div v-if="loading" class="loading">
      加载中...
    </div>
    <div v-else-if="!moment" class="no-moment">
      动态不存在或已被删除
    </div>
    <div v-else class="moment-detail">
      <div class="header-section">
        <div class="title-container">
          <el-icon class="title-icon"><Notification /></el-icon>
          <h2 class="title-text">动态详情</h2>
        </div>
        <el-button class="back-btn" type="primary" plain @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回上一页
        </el-button>
      </div>
      <div class="moment-content">
        <div class="user-info">
          <img :src="moment.userAvatar" alt="User Avatar" class="user-avatar" />
          <span class="user-name">{{ moment.userName }}</span>
        </div>
        <p><strong>{{ moment.content }}</strong></p>
        <p v-if="moment.picUrlList && moment.picUrlList.length > 0" class="moment-images">
          <img v-for="(pic, index) in moment.picUrlList" :key="index" :src="pic" alt="Moment Image" class="fixed-size-image" @click="openImageViewer(pic)" />
        </p>
        <p class="moment-date">{{ formatDate(moment.createdTime) }}</p>
      </div>

      <el-card shadow="never" class="comment-input-card">
        <div class="comment-editor">
          <el-input
              v-model="newCommentText"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
              maxlength="500"
              show-word-limit
              resize="none"
              class="comment-textarea"
          />

          <div class="editor-toolbar">
            <div class="toolbar-left">
              <!-- 修复后的表情按钮 -->
              <button class="emoji-trigger" @click.stop="toggleEmojiPicker($event)">
                😀
              </button>

              <!-- 修复后的图片上传 -->
              <el-upload
                  :action="baseUrl + '/files/upload'"
                  :limit="5"
                  multiple
                  list-type="picture-card"
                  :file-list="newCommentData.uploadedPics"
                  :on-success="handleUploadSuccess"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </div>

            <el-button
                type="primary"
                @click="addComment"
                :disabled="!newCommentText.trim() && newCommentData.uploadedPics.length === 0"
                class="send-reply-btn"
            >
              <el-icon><Position /></el-icon>
              发表评论
            </el-button>
          </div>

          <!-- 修复后的表情选择器 -->
          <transition name="fade">
            <div
                v-if="showEmojiPicker"
                class="emoji-picker-container"
            >
              <VEmojiPicker
                  :native="true"
                  @select="onSelectEmoji"
                  :disable-skin-tones="true"
                  theme="light"
              />
            </div>
          </transition>
        </div>
      </el-card>

      <h3>评论列表</h3>
      <div v-if="commentsLoading" class="loading-comments">
        加载评论中...
      </div>
      <div v-else-if="comments.length === 0" class="no-comments">
        暂无评论
      </div>
      <div v-else class="comment-list">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="user-info">
            <img :src="comment.avatar" alt="User Avatar" class="user-avatar" />
            <span class="user-name">{{ comment.userName }}</span>
          </div>
          <p><strong>{{ comment.content }}</strong></p>
          <p v-if="comment.picUrlList && comment.picUrlList.length > 0" class="comment-images">
            <img v-for="(pic, index) in comment.picUrlList" :key="index" :src="pic" alt="Comment Image" class="fixed-size-image" @click="openImageViewer(pic)" />
          </p>
          <div class="comment-actions">
            <span class="time">{{ formatDate(comment.createdTime) }}</span>
            <button class="action-btn reply" @click="toggleReply(comment)">回复</button>
            <button class="action-btn fold" @click="toggleFold(comment)">
              {{ comment.isFolded ? '展开' : '折叠' }}
            </button>
            <button v-if="canDelete(comment)" class="action-btn delete" @click="deleteComment(comment)">删除</button>
          </div>
          <div v-if="comment.showReply" class="reply-section">
            <textarea v-model="comment.replyText" placeholder="回复..." maxlength="500"></textarea>
            <div class="reply-controls">
              <div class="controls-left">
                <button class="emoji-trigger" @click.stop="toggleReplyEmojiPicker(comment)">😀</button>
                <transition name="fade">
                  <div v-if="comment.showReplyEmojiPicker" class="emoji-picker-container">
                    <VEmojiPicker
                        :native="true"
                        @select="(emoji) => onSelectReplyEmoji(comment, emoji)"
                        :disable-skin-tones="true"
                        theme="light"
                    />
                  </div>
                </transition>
                <el-upload
                    class="reply-upload"
                    :action="baseUrl + '/files/upload'"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :before-upload="beforeUpload"
                    :on-success="(response, file, fileList) => handleFileUpload(comment, response, file, fileList)"
                    :limit="5"
                    :on-exceed="handleExceed"
                    multiple
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </div>
              <el-button
                  class="send-reply-btn"
                  type="primary"
                  size="small"
                  @click="sendReply(comment)"
              >
                <el-icon><Position /></el-icon>
                发送
              </el-button>
            </div>
          </div>
          <div v-if="!comment.isFolded && comment.children && comment.children.length > 0" class="replies">
            <div v-for="reply in comment.children" :key="reply.id" class="reply-item">
              <div class="user-info">
                <img :src="reply.avatar" alt="User Avatar" class="user-avatar" />
                <span class="user-name">{{ reply.userName }}</span>
              </div>
              <p><strong>{{ reply.content }}</strong></p>
              <p v-if="reply.picUrlList && reply.picUrlList.length > 0" class="comment-images">
                <img v-for="(pic, index) in reply.picUrlList" :key="index" :src="pic" alt="Reply Image" class="fixed-size-image" @click="openImageViewer(pic)" />
              </p>
              <div class="reply-date-container">
                <span class="comment-date">{{ formatDate(reply.createdTime) }}</span>
                <el-button
                    v-if="canDelete(reply)"
                    class="action-btn delete"
                    type="danger"
                    link
                    size="small"
                    @click="deleteComment(reply)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <!-- 图片查看器 -->
    <el-image-viewer
        v-if="imageDialogVisible"
        :url-list="[clickedImageUrl]"
        @close="imageDialogVisible = false"
    />
  </div>
</template>

<script setup>
import request from "@/utils/request.js";
import {ref, onMounted} from 'vue';
import {useRoute} from 'vue-router';
import dayjs from 'dayjs';
import {ElMessage, ElDialog} from "element-plus";
import VEmojiPicker from 'vue3-emoji-picker';
import 'vue3-emoji-picker/css';
import {ArrowLeft, Delete, Notification, Plus, Position, Promotion} from '@element-plus/icons-vue';
import {useRouter} from 'vue-router';

const route = useRoute();
const moment = ref(null);
const comments = ref([]);
const newCommentText = ref('');
const loading = ref(true);
const commentsLoading = ref(true);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const baseUrl = import.meta.env.VITE_BASE_URL;
const router = useRouter();
const emojiTriggerRef = ref(null)

const handleUploadSuccess = (response) => {
  if (response.code === '200') {
    newCommentData.value.uploadedPics.push({
      url: response.data,
      name: `image_${Date.now()}`
    })
  }
}
// 获取用户ID
const user = JSON.parse(localStorage.getItem("user") || '{}');
const currentUserId = user.id;

const goBack = () => {
  router.go(-1); // 返回上一页
};

// 添加 emoji 选择器相关状态
const showEmojiPicker = ref(false);

const toggleEmojiPicker = () => {
  showEmojiPicker.value = !showEmojiPicker.value;
};

// 处理 emoji 选择
const onSelectEmoji = (emoji) => {
  if (emoji.i) {
    newCommentText.value += emoji.i;  // 使用 emoji 的 Unicode 字符
  }
  showEmojiPicker.value = false;  // 选择后自动关闭
};

const loadMomentDetails = () => {
  const id = route.query.id;
  if (!id) {
    ElMessage.error('动态ID未找到');
    loading.value = false;
    return;
  }

  request.get(`/circle/share/moment/selectById/${id}`).then(res => {
    if (res.code === '200') {
      console.log('加载动态详情成功：', res);
      moment.value = res.data || null;
      loadComments(id);
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    ElMessage.error('加载动态详情失败，请稍后再试');
    console.error(err);
  }).finally(() => {
    loading.value = false;
  });
};

const loadComments = (momentId) => {
  const payload = {
    id: parseInt(momentId)
  };

  request.post('/circle/share/comment/list', payload).then(res => {
    if (res.code === '200') {
      console.log('加载评论成功：', res);
      comments.value = res.data.map(comment => ({
        ...comment,
        showReply: false,
        isFolded: true,
        uploadedPics: [],
        picUrlList: comment.picUrlList || [], // 确保 picUrlList 存在
        showReplyEmojiPicker: false // 新增字段用于控制回复中的 emoji picker 显示
      }));
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    ElMessage.error('加载评论失败，请稍后再试');
    console.error(err);
  }).finally(() => {
    commentsLoading.value = false;
  });
};

const newCommentData = ref({
  content: '',
  uploadedPics: []
});

const addComment = () => {
  if (!newCommentText.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }

  const payload = {
    momentId: parseInt(route.query.id),
    replyType: 1,
    content: newCommentText.value,
    picUrlList: newCommentData.value.uploadedPics || []
  };

  request.post('/circle/share/comment/save', payload).then(res => {
    if (res.code === '200') {
      ElMessage.success('评论成功');
      newCommentText.value = '';
      newCommentData.value.uploadedPics = [];
      loadComments(route.query.id); // 刷新评论列表
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    ElMessage.error('评论失败，请稍后再试');
    console.error(err);
  });
};

const toggleReply = (item) => {
  item.showReply = !item.showReply;
};

const sendReply = (parentComment) => {
  if (!parentComment.replyText.trim() && (!parentComment.uploadedPics || parentComment.uploadedPics.length === 0)) {
    ElMessage.warning('回复内容和图片至少一项不能为空');
    return;
  }

  const payload = {
    momentId: parseInt(route.query.id),
    replyType: 2,
    targetId: parseInt(parentComment.id),
    content: parentComment.replyText,
    picUrlList: parentComment.uploadedPics || []
  };

  request.post('/circle/share/comment/save', payload).then(res => {
    if (res.code === '200') {
      ElMessage.success('回复成功');
      parentComment.replyText = '';
      parentComment.uploadedPics = [];
      loadComments(route.query.id); // 刷新评论列表
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    ElMessage.error('回复失败，请稍后再试');
    console.error(err);
  });
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('单个文件大小不能超过 10MB!');
  }
  return isLt10M;
};

const handleFileUpload = (comment, response, file, fileList) => {
  if (response.code === '200') {
    console.log('图片上传成功：', response);
    if (!comment.uploadedPics) {
      comment.uploadedPics = [];
    }
    comment.uploadedPics.push(response.data);
  } else {
    ElMessage.error('图片上传失败，请稍后再试');
  }
};

const handleRemove = (file, fileList) => {
  const removedUrl = file.response.data;
  const comment = findCommentByPicUrl(comments.value, removedUrl);
  if (comment) {
    comment.uploadedPics = comment.uploadedPics.filter(url => url !== removedUrl);
  }
};

const findCommentByPicUrl = (comments, picUrl) => {
  for (const comment of comments) {
    if (comment.uploadedPics && comment.uploadedPics.includes(picUrl)) {
      return comment;
    }
    if (comment.children) {
      const foundInChildren = findCommentByPicUrl(comment.children, picUrl);
      if (foundInChildren) {
        return foundInChildren;
      }
    }
  }
  return null;
};

const handleExceed = (files, fileList) => {
  ElMessage.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
};

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

const toggleFold = (comment) => {
  comment.isFolded = !comment.isFolded;
};

const canDelete = (comment) => {
  return comment.userId === currentUserId;
};

const deleteComment = (comment) => {
  const payload = {
    id: comment.id,
    replyType: comment.replyType
  };

  request.post('/circle/share/comment/remove', payload).then(res => {
    if (res.code === '200') {
      ElMessage.success('删除成功');
      loadComments(route.query.id); // 刷新评论列表
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    ElMessage.error('删除失败，请稍后再试');
    console.error(err);
  });
};

// 图片查看器相关变量
const clickedImageUrl = ref('');
const imageDialogVisible = ref(false);

// 打开图片查看器
const openImageViewer = (imageUrl) => {
  clickedImageUrl.value = imageUrl;
  imageDialogVisible.value = true;
};

// 回复区域的 emoji picker 控制
const toggleReplyEmojiPicker = (comment) => {
  comment.showReplyEmojiPicker = !comment.showReplyEmojiPicker;
};

// 处理回复中的 emoji 选择
const onSelectReplyEmoji = (comment, emoji) => {
  if (emoji.i) {
    comment.replyText += emoji.i;  // 使用 emoji 的 Unicode 字符
  }
  comment.showReplyEmojiPicker = false;  // 选择后自动关闭
};

onMounted(() => {
  loadMomentDetails();
});
</script>

<style scoped>
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  position: relative;
  padding-bottom: 12px;
}

/* 标题容器 */
.title-container {
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
}

/* 分割线 */
.header-section::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: var(--el-border-color);
}

/* 标题图标 */
.title-icon {
  font-size: 24px;
  color: var(--el-color-primary);
}

/* 标题文字 */
.title-text {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

/* 返回按钮 */
.back-btn {
  padding: 10px 16px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s;
}
.comment-input-card {
  margin: 20px 0;
  border-radius: 8px;
  background: #fafafa;
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  position: relative;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 表情按钮 */
.emoji-trigger {
  width: 36px;
  height: 36px;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  background: white;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
}

.emoji-trigger:hover {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
}

/* 图片上传 */
:deep(.el-upload-list--picture-card) {
  margin: 0;
}

:deep(.el-upload--picture-card) {
  width: 36px;
  height: 36px;
  line-height: 38px;
}

/* 表情选择器定位 */
.emoji-picker-container {
  position: absolute;
  z-index: 1000;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border-radius: 8px;
  overflow: hidden;
}
.reply-controls {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
}

.controls-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 统一元素高度 */
.emoji-trigger,
:deep(.reply-upload .el-upload),
.send-reply-btn {
  height: 32px;
  width: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.emoji-trigger {
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  background: white;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
}

:deep(.reply-upload .el-upload) {
  border-radius: 6px;
}

.send-reply-btn {
  width: auto;
  padding: 8px 16px;
  border-radius: 6px;
}

/* 调整上传图标大小 */
:deep(.reply-upload .el-icon) {
  font-size: 14px;
}

/* 日期和删除按钮布局 */
.reply-date-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.comment-date {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}


/* 保持原有样式优化 */
.reply-section textarea {
  width: 100%;
  min-height: 80px;
  padding: 8px 12px;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  resize: vertical;
  margin-bottom: 8px;
}

.reply-section textarea:focus {
  border-color: var(--el-color-primary);
  outline: none;
}

/* 调整表情选择器层级 */
.emoji-picker-container {
  z-index: 2000;
  margin-top: 8px;
}



/* 保持原有响应式 */
@media (max-width: 768px) {
  .controls-left {
    gap: 6px;
  }

  :deep(.reply-upload .el-upload) {
    width: 28px;
    height: 28px;
  }

  .emoji-trigger {
    width: 28px;
    height: 28px;
  }
}
.back-btn:hover {
  background: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-5);
}
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f7f7f7;
  border-radius: 8px;
}

.loading, .loading-comments {
  text-align: center;
  font-size: 16px;
  color: #888;
}

.no-moment, .no-comments {
  text-align: center;
  font-size: 16px;
  color: #e8e7e7;
}

.moment-detail {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 15px;
}

.moment-content p {
  font-size: 16px;
  color: #333;
}

.fixed-size-image {
  width: 150px; /* 设置固定的宽度 */
  height: 150px; /* 设置固定的高度 */
  object-fit: cover; /* 确保图片内容填充盒子 */
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.moment-images,
.comment-images {
  display: flex;
  flex-wrap: wrap;
}

.moment-date {
  font-size: 14px;
  color: #dddddd;
  margin-top: 10px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.comment-item:last-child {
  border-bottom: none;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
}

.user-name {
  font-weight: bold;
  color: #333;
}

.comment-item p {
  margin: 5px 0;
}

/* 原样式保留，新增以下按钮样式 */
.comment-actions {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 13px;
}

.time {
  color: #999;
  margin-right: 8px;
}

.action-btn {
  padding: 4px 8px;
  border: none;
  background: none;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.action-btn::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: -2px;
  height: 1px;
  background: currentColor;
  transform: scaleX(0);
  transition: transform 0.2s;
}

.action-btn:hover {
  color: #0078d4;
}

.action-btn:hover::after {
  transform: scaleX(1);
}

/* 不同按钮颜色 */
.reply { color: #666; }
.fold { color: #666; }
.delete { color: #ff4d4f; }

/* 移动端适配 */
@media (max-width: 768px) {
  .comment-actions {
    gap: 8px;
  }

  .action-btn {
    padding: 2px 6px;
    font-size: 12px;
  }
}

.comment-date-with-reply span {
  margin-right: 10px;
}
.send-reply-btn {
  margin-left: auto;
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.3s;
}

.send-reply-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}



/* 调整子评论布局 */
.reply-item {
  position: relative;
  padding: 12px;
  margin: 8px 0;
  background: #f8f9fa;
  border-radius: 6px;
}

.reply-item .user-info {
  margin-bottom: 8px;
}

.reply-item .comment-date {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

/* 图片样式保持原样 */
.fixed-size-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 8px;
  border-radius: 4px;
  cursor: zoom-in;
  transition: transform 0.2s;
}

.fixed-size-image:hover {
  transform: scale(1.02);
}


.reply-section {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
}

.reply-section textarea {
  width: calc(100% - 90px);
  height: 40px;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #ccc;
  font-size: 14px;
  resize: vertical;
}


.reply-icons button {
  margin-right: 10px;
}

.send-reply-btn {
  padding: 10px 20px;
  border: none;
  background-color: #0078d4;
  border-radius: 5px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  margin-left: 5px;
  transition: background-color 0.3s ease;
}

.send-reply-btn:hover {
  background-color: #005c9a;
}

.add-comment-section {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.add-comment-section textarea {
  width: 100%;
  height: 100px;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #ccc;
  font-size: 16px;
  resize: vertical;
}

.publish-comment-btn {
  margin-top: 10px;
  padding: 10px 20px;
  border: none;
  background-color: #0078d4;
  border-radius: 5px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.replies {
  margin-left: 30px;
}

.reply-item {
  margin-bottom: 10px;
}


</style>
